package com.sptpc.learnspring.service;


import com.sptpc.learnspring.model.Category;
import com.sptpc.learnspring.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    public Category saveCategory(String name){
        return categoryRepository.save(Category.builder().name(name).build());
    }

    public Category saveCategory(Category category){
        return categoryRepository.save(category);
    }

    public List<Category> findAll() {

        return categoryRepository.findAll(Sort.by(Sort.Direction.DESC, "createTime"));
    }

//    public Category findOne(String name){
//        ExampleMatcher matcher = ExampleMatcher.matching()
//                .withIgnoreCase("name");
//        Optional<Category> category = categoryRepository
//                .findOne(Example.of(Category.builder().name(name).build(), matcher));
//        if (category.isPresent()){
//            return category.get();
//        }else {
//            return null;
//        }
//    }

    public Category findOne(String name){
        Optional<Category> category = categoryRepository.findCategoryByNameLike(name);
        if (category.isPresent()){
            return category.get();
        }else {
            return null;
        }
    }

    public Category findOne(Long id){
        Optional<Category> category = categoryRepository.findById(id);
        if (category.isPresent()){
            return category.get();
        }else {
            return null;
        }
    }

    public Category update(long id, String newName) {
        Optional<Category> category = categoryRepository.findById(id);
        if(category.isPresent()){
            Category oldCategory = category.get();
            oldCategory.setName(newName);
            return categoryRepository.saveAndFlush(oldCategory);
        }else {
            return null;
        }
    }

    public boolean delete(long id) {
        try {
            categoryRepository.deleteById(id);
            return true;
        }catch (Exception ex){
            return false;
        }
    }
}
